<!--
* description: 车辆管理-车辆报废设置
* author: ligy
* createdDate: 2020-11-18
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :dynamic-is-fix-choose="false"
      :dynamic-is-fix-index="false"
      :dynamic-api-style="'restful'"
      :callback-obj="callbackObj"
    />
  </div>
</template>

<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import { exportExcel } from '@/utils/getTimeString'
import api from '@/api/vehicleManagement'

export default {
  name: 'VehicleScrapSetting',
  components: {
    OneTableTemplate
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, 'supplierMessage-edit'], () => {
      next()
    })
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      apiConfig: api.vehicleScrapSetting,
      // 动态生成网格列
      tableCols: this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
        : [
          {
            prop: 'discardSetName',
            label: '是否已设置',
            align: 'center'
          },
          {
            prop: '',
            label: '报废类型',
            isComponent: true,
            // isSlot:true,
            isColComp: true,
            comps: [
              {
                isAsync: true,
                disabled: true,
                compKey: 'compKey10' + this.$utils.generateId(),
                codeField: 'discardType',
                textField: 'discardTypeName',
                lookuptype: 'VE0211',
                component: () => import('@/components/org/commonSelect'),
                type: 'dropdownList',
                rowFileds: 'disabled:discardSetName-是',
                customObj: {
                  selectType: '1'
                }
              }
            ],
            width: 100
          },
          {
            prop: '',
            label: '报废原因',
            isComponent: true,
            comps: [
              {
                compKey: 'compKey5' + this.$utils.generateId(),
                disabled: true,
                codeField: 'discardDesc',
                component: () => import('@/components/org/commonInput'),
                type: 'inputText',
                rowFileds: 'disabled:discardSetName-是'

              }
            ],
            width: 100
          },
          {
            prop: 'discardSetNamekuang',
            label: '车辆类型',
            align: 'center',
            width: 100
          },
          {
            prop: 'discardDate',
            label: '报废时间',
            align: 'center',
            width: 140
          },
          {
            prop: 'vin',
            label: 'VIN码',
            align: 'center',
            width: 140
          },
          {
            prop: 'carSeriesCn',
            label: '车系',
            align: 'center'
          },
          {
            prop: 'carConfigCn',
            label: '基础车型',
            align: 'center'
          },
          {
            prop: 'optionalPagName',
            label: '选装包',
            align: 'center'
          },
          {
            prop: 'carColorName',
            label: '车身颜色',
            align: 'center'
          },
          {
            prop: 'carIncolorName',
            label: '内饰颜色',
            align: 'center'
          },
          {
            prop: 'produceDate',
            label: '出厂日期',
            align: 'center',
            width: 140
          },
          {
            prop: 'prdduceAddr',
            label: '产地',
            align: 'center'
          },
          {
            prop: 'carStatusName',
            label: '车辆状态',
            align: 'center'
          }
        ],
      tableComponents:
      this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
        : [
        // VIN码
          {
            compKey: 'compKey1',
            labelName: 'VIN码：',
            codeField: 'vin',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            span: 6
          },
          // 车辆类型
          {
            compKey: 'compKey3',
            labelName: '车辆类型：',
            codeField: 'discardSet',
            component: () => import('@/components/org/LookupValue'),
            type: 'dropdownList',
            isMust: true,
            span: 6,
            oFields: 'discardSet,discardSetName',
            options: [
              { discardSet: '0', discardSetName: '未报废' },
              { discardSet: '1', discardSetName: '已报废' }
            ]
          },
          {
            compKey: 'compKey4',
            labelName: '报废时间：',
            codeField: 'discardDate',
            component: () => import('@/components/org/datePicker/andtDatePicker'),
            type: 'YYYY-MM-DD HH:mm:ss',
            // type: 'twoDatePicker',
            hhmmss: true, // 默认有时分秒
            format: 'yyyy-MM-dd',
            dateOptionsType: '0',
            isMul: false,
            isMust: true
          }
        ],
      tableButtons: [
        {
          conmpKey: 'btenKey1',
          type: '',
          size: 'small',
          text: '车辆报废设置',
          clickEvent: () => this.send(),
          position: 'left'
        },
        {
          conmpKey: 'btenKey2',
          type: '',
          size: 'small',
          clickEvent: () => this.exportExcel111(),
          text: this.$t('sys.button.export'),
          name: 'export',
          position: 'left' // 导出
        },
        {
          conmpKey: 'btenKey3',
          type: 'primary',
          size: 'small',
          text: this.$t('sys.button.query'), // 查询
          name: 'search', // 按钮图标样式
          clickEvent: () => this.queryTable(1),
          position: 'right'
        },
        {
          conmpKey: 'btenKey4',
          type: '',
          size: 'small',
          text: this.$t('sys.button.reset'),
          name: 'reset',
          clickEvent: () => this.reset(),
          position: 'right'
        }
      ],
      formField: this.$utils.getFormField(this, {
        discardSet: '',
        vin: '',
        discardDate: '',
        discardDesc: '',
        discardTypeName: '',
        startTime: '',
        endTime: '',
        discardType: ''
      }),
      selectionList: [],
      list: [],
      indexlist: [],
      callbackObj: {
        // 当选择项发生变化时触发该函数updateControlId    discardType     vin      discardDesc    discardSet

        onCheckSelectChange: (selection) => {
          this.selectionList = selection
          this.indexlist = this.selectionList.reduce((pre, cur) => {
            // pre.push({ carStoreId: cur.carStoreId,
            //   updateControlId: cur.updateControlId,
            //   VINCode: cur.VINCode,
            //   lookupValueCode: cur.lookupValueCode
            // })
            pre.push(cur.index)
            return pre
          }, [])
        }
      }
    }
  },
  watch: {
    'formField.discardDate'(newVal, oldVal) {
      const dataArr = newVal.split(',')
      this.formField.startTime = dataArr[0]
      this.formField.endTime = dataArr[1]
      const startTime = new Date(dataArr[0])
      const endTime = new Date(dataArr[1])
      if (startTime.getTime() - endTime.getTime() > 0) return this.$message.error('开始时间不能大于结束时间!')
    }

  },
  created() {

  },
  mounted() {
    setTimeout(() => {
      this.queryTable(1)
    }, 0)
  },
  methods: {
    // 设置表格选择框 是否禁用
    getSelectable(row, index) {
      if (row.discardSetName === '否') {
        return true
      }
    },
    // 导出
    exportExcel111() {
      exportExcel(this.formField, api.vehicleScrapSettingExport.APIUrl, '', '车辆报废设置')
      // const fileName = this.$utils.fileNameWithTime('车辆报废设置.xlsx')
      // this.$requestAPI({
      //   apiUrl: api.vehicleScrapSettingExport.APIUrl,
      //   variables: { dataType: 'excel' }
      // }).then(res => {
      //   this.$utils.downloadFile(res, fileName)
      // }).catch(err => {
      //   console.log(err)
      // })
    },
    // 车辆报废设置
    send() {
      var lock
      var datalist = []
      this.indexlist.forEach(item => {
        datalist.push(this.$refs.multipleTable.list[item])
      })
      this.list = datalist.reduce((pre, cur) => {
        pre.push({
          discardType: cur.discardType,
          salePlanCode: cur.salePlanCode,
          carId: cur.carId,
          updateControlId: cur.updateControlId,
          vin: cur.vin,
          discardSet: cur.discardSet,
          discardDesc: cur.discardDesc
        })
        return pre
      }, [])
      if (this.list.length === 0) {
        this.$message('请选择!')
        lock = false
      } else {
        // 发送请求
        for (const k in this.list) {
          if (!this.list[k].discardDesc && !this.list[k].discardType) {
            this.$message('漏填报废类型和报废原因!')
            lock = false
          } else if (!this.list[k].discardDesc) {
            this.$message('漏填报废原因!')
            lock = false
          } else if (!this.list[k].discardType) {
            this.$message('漏填报废类型!')
            lock = false
          } else if (this.list[k].discardDesc.length >= 90) {
            this.$message('报废原因过长请梳理')
            lock = false
          } else {
            lock = true
          }
        }
        if (lock === true) {
          this.$requestAPI(this.$getParams({
            apiConfig: api.updateScrapcar,
            variables: { list: this.list }
          })).then(response => {
            if (response.result === '0') {
              if (response.msg) {
                this.$message({
                  message: response.msg,
                  type: 'warn',
                  uration: 2000
                })
              }
            }
            // 返回json
            this.$message({ message: response.msg })
            this.$refs['multipleTable'].$refs['multipleTable'].clearSelection()
            this.formField.vin = ''
            this.formField.discardDesc = ''
            this.formField.discardType = ''
            this.formField.updateControlId = ''
            setTimeout(() => {
              this.queryTable(1)
            }, 0)
          }).catch(() => {
            this.$refs['multipleTable'].listLoading = false
          })
        }
      }
    }
  }
}
</script>

<style></style>
